package com.pug.ksd.cloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022/3/5$ 20:24$
 */
@Component
@Slf4j
public class AccessTokenFilter extends ZuulFilter implements PugZuulFilter{


    @Override
    public String filterType() {
        return ZUUL_PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 1: 通过zuul提供的RequestContext上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        // 2 ：通过RequestContext获取请求和相应对象
        HttpServletRequest request = currentContext.getRequest();
        // 3 : 获取请求参数是否存在token
        log.info("------------------------token filter----------------------");
        String token = request.getParameter("token");
        // 4 : 判断你当前是否存在token，如果不存在
        if (StringUtils.isEmpty(token)) {
            log.info("token is empty!!!");
            // 代表请求结束，不在继续下级的传递
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);
            currentContext.setResponseBody("{\"result\":\"token is empty!!!\"}");
            currentContext.getResponse().setContentType("text/html;charset=utf-8");
        } else {
            log.info("token is success!!!");
        }
        // 5：如果存在返回null. null 代表意思：继续执行下一个过滤器
        return null;
    }
}
